package com.eboss2.sbs.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.calendar.CalendarGridView;
import com.mytools.tool.calendar.CalendarGridViewAdapter;
import com.mytools.tool.calendar.NumberHelper;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.TimeUtil;
import com.tool.utils.utils.ToastUtils;

import java.util.Calendar;
import java.util.Date;

public class ChooseDateActivity extends BaseActivity implements OnTouchListener, View.OnClickListener {

	public static int CHOOSE_ALL_DATE = 0;
	public static int CHOOSE_BEFORE_TODAY = 1;
	public static int CHOOSE_AFTER_TODAY = 2;
	private int chooseType = CHOOSE_ALL_DATE;
	
	public static String PARA_SELECTED_DATE = "PARA_SELECTED_DATE";
	public static String FORMAT_DATE = "yyyy-MM-dd";
	
    private static final int CAL_LAYOUT_ID = 55;
    
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private Animation slideLeftIn;
    private Animation slideLeftOut;
    private Animation slideRightIn;
    private Animation slideRightOut;
    private ViewFlipper viewFlipper;
    
    GestureDetector mGesture = null;

    private RelativeLayout mCalendarMainLayout;

    private GridView firstGridView;
    private GridView currentGridView;
    private GridView lastGridView;
    
    private Calendar calStartDate = Calendar.getInstance();
    private Calendar calSelected = Calendar.getInstance();
    private Calendar calToday = Calendar.getInstance();
    
    private CalendarGridViewAdapter currentGridAdapter;
    private CalendarGridViewAdapter firstGridAdapter;
    private CalendarGridViewAdapter lastGridAdapter;
    private int mMonthViewCurrentMonth = 0;
    private int mMonthViewCurrentYear = 0;
    private int iFirstDayOfWeek = Calendar.MONDAY;
    
    private String toDate;
    private String fromDate;
    
    //private ImageView img_animal;

    @SuppressLint("ClickableViewAccessibility")
	@Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGesture.onTouchEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_choose_date);
        MyActivityManager.getInstance().addActivity(this);



        chooseType = getIntent().getIntExtra("chooseType", CHOOSE_ALL_DATE);
        
        String query_date = getIntent().getStringExtra("PARA_SELECTED_DATE");
        Date date_selected = TimeUtil.getDateFromString(query_date, FORMAT_DATE);
        
        toDate = getIntent().getStringExtra("toDate");
        fromDate = getIntent().getStringExtra("fromDate");
        
        calStartDate.setTime(date_selected);
        calSelected.setTime(date_selected);
        calToday.setTime(date_selected);
        
        initView();
        updateStartDateForMonth();

        generateContetView(mCalendarMainLayout);
        
        slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);

        slideLeftIn.setAnimationListener(animationListener);
        slideLeftOut.setAnimationListener(animationListener);
        slideRightIn.setAnimationListener(animationListener);
        slideRightOut.setAnimationListener(animationListener);

        mGesture = new GestureDetector(this, new GestureListener());
    }

    private void initView() {
    	//img_animal = (ImageView) findViewById(R.id.img_animal);
        //mDayMessage = (TextView) findViewById(R.id.h_tv_title);
        mCalendarMainLayout = (RelativeLayout) findViewById(R.id.calendar_main);
        
        showView(R.id.h_btn_previous, true);
        showView(R.id.h_btn_next, true);
        showView(R.id.h_ly_tv_sure, true);
        setTvText(R.id.h_tv_sure, "今日");
        
        findViewById(R.id.h_ly_img_back).setOnClickListener(this);
        findViewById(R.id.h_btn_previous).setOnClickListener(this);
        findViewById(R.id.h_btn_next).setOnClickListener(this);
        findViewById(R.id.h_ly_tv_sure).setOnClickListener(this);
        findViewById(R.id.btn_confirm).setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
    	switch (v.getId()) {
	    	case R.id.h_ly_img_back:
	    		finish();
	    		break;
			case R.id.h_ly_tv_sure:
				JumpToSpecailDay(Calendar.getInstance().getTime());
				break;
			case R.id.h_btn_previous:
	            viewFlipper.setInAnimation(slideRightIn);
	            viewFlipper.setOutAnimation(slideRightOut);
	            viewFlipper.showPrevious();
	            setPrevViewItem();
				break;
			case R.id.h_btn_next:
	            viewFlipper.setInAnimation(slideLeftIn);
	            viewFlipper.setOutAnimation(slideLeftOut);
	            viewFlipper.showNext();
	            setNextViewItem();
				break;
			case R.id.btn_confirm:
	        	String date_string = TimeUtil.getStringFromDate(calSelected, FORMAT_DATE);
	        	setResult(RESULT_OK, (new Intent()).putExtra(PARA_SELECTED_DATE, date_string));
	        	finish();
	        	break;
			default: break;
		}
    }
    
    private void JumpToSpecailDay(Date date){
    	
        Date today = new Date();
        Date data_cmp = TimeUtil.getProtoDate(date);
        Date today_cmp = TimeUtil.getProtoDate(today);
        
        if(chooseType==CHOOSE_BEFORE_TODAY){
        	if(data_cmp.after(today_cmp)){
//        	    toast("日期不能大于今天");
                ToastUtils.showShort(mContext, "日期不能大于今天");
        	    return;
        	}
        }
        else if(chooseType==CHOOSE_AFTER_TODAY){
        	if(data_cmp.before(today_cmp)){
//        	    toast("日期不能小于今天");
                ToastUtils.showShort(mContext, "日期不能小于今天");
        	    return;
        	}
        }
        if(!StringUtil.isNull(fromDate)){
        	Date dateFrom = TimeUtil.getDateFromString(fromDate, FORMAT_DATE);
        	if(data_cmp.before(dateFrom)){
//        	    toast("日期不能早于查询起始时间");
                ToastUtils.showShort(mContext, "日期不能早于查询起始时间");
        	    return;
        	}
        }
        if(!StringUtil.isNull(toDate)){
        	Date dateTo = TimeUtil.getDateFromString(toDate, FORMAT_DATE);
        	if(data_cmp.after(dateTo)){
//        	    toast("日期不能晚于查询终止时间");
                ToastUtils.showShort(mContext, "日期不能晚于查询终止时间");
        	    return;
        	}
        }
    	
        calStartDate.setTime(date);
        calSelected.setTime(date);
        calToday.setTime(date);
        updateStartDateForMonth();
        generateContetView(mCalendarMainLayout);
        
    }

    private void generateContetView(RelativeLayout layout) {
        viewFlipper = new ViewFlipper(this);
        viewFlipper.setId(CAL_LAYOUT_ID);
        calStartDate = getCalendarStartDate();
        
        CreateGirdView();
		RelativeLayout.LayoutParams params_cal = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        layout.addView(viewFlipper, params_cal);

        LinearLayout br = new LinearLayout(this);
		RelativeLayout.LayoutParams params_br = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1);
        params_br.addRule(RelativeLayout.BELOW, CAL_LAYOUT_ID);
        br.setBackgroundColor(getResources().getColor(R.color.calendar_background));
        layout.addView(br, params_br);
    }

    private void CreateGirdView() {

        Calendar firstCalendar = Calendar.getInstance();
        Calendar currentCalendar = Calendar.getInstance();
        Calendar lastCalendar = Calendar.getInstance();
        
        firstCalendar.setTime(calStartDate.getTime());
        currentCalendar.setTime(calStartDate.getTime());
        lastCalendar.setTime(calStartDate.getTime());

        firstGridView = new CalendarGridView(mContext);
        firstCalendar.add(Calendar.MONTH, -1);
        firstGridAdapter = new CalendarGridViewAdapter(this, firstCalendar);
        firstGridAdapter.setSelectedDate(calSelected);
        firstGridView.setAdapter(firstGridAdapter);
        firstGridView.setId(CAL_LAYOUT_ID);

        currentGridView = new CalendarGridView(mContext);
        currentGridAdapter = new CalendarGridViewAdapter(this, currentCalendar);
        currentGridAdapter.setSelectedDate(calSelected);
        currentGridView.setAdapter(currentGridAdapter);
        currentGridView.setId(CAL_LAYOUT_ID);

        lastGridView = new CalendarGridView(mContext);
        lastCalendar.add(Calendar.MONTH, 1);
        lastGridAdapter = new CalendarGridViewAdapter(this, lastCalendar);
        lastGridAdapter.setSelectedDate(calSelected);
        lastGridView.setAdapter(lastGridAdapter);
        lastGridView.setId(CAL_LAYOUT_ID);

        currentGridView.setOnTouchListener(this);
        firstGridView.setOnTouchListener(this);
        lastGridView.setOnTouchListener(this);

        if (viewFlipper.getChildCount() != 0) {
            viewFlipper.removeAllViews();
        }

        viewFlipper.addView(currentGridView);
        viewFlipper.addView(lastGridView);
        viewFlipper.addView(firstGridView);

        String s = calStartDate.get(Calendar.YEAR) + "年" + NumberHelper.LeftPad_Tow_Zero(calStartDate.get(Calendar.MONTH) + 1)+"月";
        setTvText(R.id.h_tv_title, s);
//        mDayMessage.setText(s);
    }

    private void setPrevViewItem() {
        mMonthViewCurrentMonth--;
        if (mMonthViewCurrentMonth == -1) {
            mMonthViewCurrentMonth = 11;
            mMonthViewCurrentYear--;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1);
        calStartDate.set(Calendar.MONTH, mMonthViewCurrentMonth);
        calStartDate.set(Calendar.YEAR, mMonthViewCurrentYear);

    }

    private void setNextViewItem() {
        mMonthViewCurrentMonth++;
        if (mMonthViewCurrentMonth == 12) {
            mMonthViewCurrentMonth = 0;
            mMonthViewCurrentYear++;
        }
        calStartDate.set(Calendar.DAY_OF_MONTH, 1);
        calStartDate.set(Calendar.MONTH, mMonthViewCurrentMonth);
        calStartDate.set(Calendar.YEAR, mMonthViewCurrentYear);
    }

    private void updateStartDateForMonth() {
    	
        calStartDate.set(Calendar.DATE, 1);
        mMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);
        mMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);

        String s = calStartDate.get(Calendar.YEAR) + "年" + NumberHelper.LeftPad_Tow_Zero(calStartDate.get(Calendar.MONTH) + 1)+"月";
        setTvText(R.id.h_tv_title, s);
        int iDay = 0;
        int iFirstDayOfWeek = Calendar.MONDAY;
        int iStartDay = iFirstDayOfWeek;
        if (iStartDay == Calendar.MONDAY) {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
            if (iDay < 0)
                iDay = 6;
        }
        if (iStartDay == Calendar.SUNDAY) {
            iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
            if (iDay < 0)
                iDay = 6;
        }
        calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);

    }

    private Calendar getCalendarStartDate() {
        calToday.setTimeInMillis(System.currentTimeMillis());
        calToday.setFirstDayOfWeek(iFirstDayOfWeek);
        if (calSelected.getTimeInMillis() == 0) {
            calStartDate.setTimeInMillis(System.currentTimeMillis());
            calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
        } else {
            calStartDate.setTimeInMillis(calSelected.getTimeInMillis());
            calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
        }
        return calStartDate;
    }

    AnimationListener animationListener = new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {}
        @Override
        public void onAnimationRepeat(Animation animation) {}
        @Override
        public void onAnimationEnd(Animation animation) {
            CreateGirdView();
        }
    };

    class GestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    viewFlipper.setInAnimation(slideLeftIn);
                    viewFlipper.setOutAnimation(slideLeftOut);
                    viewFlipper.showNext();
                    setNextViewItem();
                    return true;

                } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    viewFlipper.setInAnimation(slideRightIn);
                    viewFlipper.setOutAnimation(slideRightOut);
                    viewFlipper.showPrevious();
                    setPrevViewItem();
                    return true;

                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            int pos = currentGridView.pointToPosition((int) e.getX(), (int) e.getY());
            LinearLayout txtDay = (LinearLayout) currentGridView.findViewById(pos + 5000);
            if (txtDay != null) {
                if (txtDay.getTag() != null) {
                    Date date = (Date) txtDay.getTag();
                    JumpToSpecailDay(date);
                }
            }
            return false;
        }
        
        @Override
        public boolean onDoubleTap(MotionEvent e) {
        	String date_string = TimeUtil.getStringFromDate(calSelected, FORMAT_DATE);
        	setResult(RESULT_OK, (new Intent()).putExtra(PARA_SELECTED_DATE, date_string));
        	finish();
        	return super.onDoubleTapEvent(e);
        }
        
    }
    
//    private void infoDisplay(){
//    	CalendarUtil cld = new CalendarUtil(calSelected);
//    	setTvText(R.id.tv_date, TimeUtil.getStringFromDate(calSelected, "yyyy��MM��dd��"));
//    	setTvText(R.id.tv_week, cld.getWeek(calSelected));
//    	setTvText(R.id.tv_nongli, cld.getNDate());
//    	String festival = cld.getNFestival();
//    	showView(R.id.tv_n_festival, !StringUtil.isNullOrEmpty(festival));
//    	setTvText(R.id.tv_n_festival, !StringUtil.isNullOrEmpty(festival)?festival:"");
//    	setTvText(R.id.tv_td_year, cld.cyclical_year()+"��");
//    	setTvText(R.id.tv_td_monthday, cld.cyclical_month()+"��  "+cld.cyclical_day()+"��");
//    	img_animal.setImageResource(cld.animalsYearImg());
//    }
    
}
